package cn.itsource.crm.web.controller;

import cn.itsource.crm.web.fileutil.FileUploadUtil;
import cn.itsource.util.AjaxResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.datatransfer.MimeTypeParseException;

@Controller
@RequestMapping("/file")
@CrossOrigin
public class FileUploadController {

    /**
     * 租户或员工注册时上传头像
     *
     * @return
     */
    @RequestMapping(value = "/logoUpload", method = RequestMethod.POST)//文件上传用POST
    @ResponseBody
    @ApiOperation(value = "租户或员工注册时上传头像", notes = "租户或员工注册时上传头像")
    //HTTP响应整体描述
    @ApiResponses({
            //HTTP响应其中1个描述
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "网络错误，请稍后")
    })
    AjaxResult logoUpload(HttpServletRequest req) {
        /*防止前端上传文件时报null异常,并不判断有没有上传文件,返回的值有可能为null*/
        MultipartFile imageFile = FileUploadUtil.isMultipart("file", req);

        String fileName = "";
        try {
            /*判断有没有上传文件*/
            if (imageFile.getSize() != 0) {
                /*执行上传 返回文件名*/
                fileName = FileUploadUtil.fileUpload(imageFile, "logoImage", req,512000L);
            }
            AjaxResult result = new AjaxResult();
            /*文件名返回给前台*/
            result.setFileName(fileName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            AjaxResult result = new AjaxResult(false);
            if(e instanceof MimeTypeParseException){
                System.out.println(e.getMessage());
                result.setMsg(e.getMessage());
            }
            if(e instanceof MaxUploadSizeExceededException){
                System.out.println(e.getMessage());
                result.setMsg("文件不能大于500K");
            }
            return result;
        }
    }

}
